// UART2.c
#include "USART.h"
#include "freertos.h"
#include "semphr.h"
extern QueueHandle_t queue;
void USART2_Init(void) {
    // ����ʱ��
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    // ��ʼ������
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;//PA2:USART2_TX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA3:USART2_RX
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // USART����
    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = 9600;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_Init(USART2, &USART_InitStructure);

    USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
    // NVIC ���ó�ʼ��

    NVIC_InitTypeDef NVIC_InitStructure;
    // ���� NVIC������ USART2���ж�
    NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; // ����USART2���ж�
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 12;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
	USART_Cmd(USART2, ENABLE);
    // ����USART2
    
}

// �����ֽ�
void USART2_SendByte(uint8_t Byte) {
    USART_SendData(USART2, Byte);

    while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
}


void printf2(char *format, ...) {
	vTaskSuspendAll();
    char strs[240];
    va_list list;
    va_start(list, format);
    vsprintf(strs, format, list);
    va_end(list);

    for (uint8_t i = 0; strs[i] != '\0'; i++) {
        USART2_SendByte(strs[i]);
    }
	xTaskResumeAll();
}

void USART2_IRQHandler(void) {
    if (USART_GetITStatus(USART2, USART_IT_RXNE) == SET) {
        volatile uint8_t temp = USART_ReceiveData(USART2);
        USART_SendData(USART2, temp);
        while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
    }
}
